package com.chengyu.core.controller.callback;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chengyu.core.dto.tencent.SceneEmpowerReqDTO;
import com.chengyu.core.entity.TblMemberEntity;
import com.chengyu.core.exception.BusinessException;
import com.chengyu.core.request.CarbonPlanetReqVo;
import com.chengyu.core.request.PointsImpowerReq;
import com.chengyu.core.response.TblPointsSceneResp;
import com.chengyu.core.result.CommonResult;
import com.chengyu.core.service.HttpRequestService;
import com.chengyu.core.service.ITblPointsImpowerService;
import com.chengyu.core.service.ITblPointsSceneService;
import com.chengyu.core.service.TblMemberService;
import com.chengyu.core.utils.NewEncryptUtils;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.nio.charset.StandardCharsets;
import java.util.*;


@RestController
@RequestMapping("/impower")
@ApiIgnore
@Slf4j
@RequiredArgsConstructor
public class TTImpowerController {

    private final ITblPointsSceneService iTblPointsSceneService;
    private final ITblPointsImpowerService tblPointsImpowerService;
    private final HttpRequestService httpRequestService;
    private final TblMemberService tblMemberService;

    final String AesKey = "Tt55nsaAsf53Xanc";

    final String ride_code_bus = "ride_code_bus";

    final String ride_code_metro = "ride_code_metro";

    @GetMapping("test")
    @ApiOperation("test")
    public CommonResult<String> getImpowerMember() throws Exception {
      return CommonResult.success("test ok");
    }

    @PostMapping("carbonPlanetImpower")
    @ApiOperation("碳碳星球授权")
    public CommonResult<Boolean> getImpowerMember(@RequestBody CarbonPlanetReqVo carbonPlanetReqVo) throws Exception {

        log.info("碳碳星球授权--->{}", JSONObject.toJSONString(carbonPlanetReqVo));


//        {"data":{"unionId":"oSWHnvi5nSIa0gETaIIFXsk3KFqY","phone":"YPjiK9Uq7jhozv3iPRItYQ=="},"sign":"F1E031AA49D0473CB47DC72ECC870826","timestamp":"1717217218"}


        JSONObject jsonObject = carbonPlanetReqVo.getData();
        String phoneStr = jsonObject.getString("phone");
        String unionId = jsonObject.getString("unionId");
        if (StrUtil.isEmpty(phoneStr)){
            throw new BusinessException("参数有误，phone不能为空");
        }
        if (StrUtil.isEmpty(unionId)){
            throw new BusinessException("参数有误，unionId不能为空");
        }
        String sgin = generateSign(carbonPlanetReqVo.getTimestamp(), phoneStr, unionId);
        Long time =Long.valueOf(carbonPlanetReqVo.getTimestamp());
        long timestamp = (System.currentTimeMillis()/1000) - time;
        log.info("checkTime---"+ timestamp);



        if (timestamp > 30){
            throw new BusinessException("参数已过期");
        }

        if (sgin.equals(carbonPlanetReqVo.getSign())) {
            throw new BusinessException("签名错误");
        }
//        try {
            List<PointsImpowerReq> list = new ArrayList<>();
            String phone = NewEncryptUtils.decrypt(phoneStr, AesKey);
            QueryWrapper<TblMemberEntity> memberEntityQueryWrapper = new QueryWrapper<>();
            memberEntityQueryWrapper.eq("phone", phone);
            TblMemberEntity memberEntity = tblMemberService.getOne(memberEntityQueryWrapper);

            log.info("memberEntity---"+ memberEntity.toString());
            log.info("memberEntity---uuid"+ memberEntity.getUuid());



            //获取减排场景
            List<TblPointsSceneResp> sceneRespList = iTblPointsSceneService.sceneList();
            TblPointsSceneResp sceneBus = sceneRespList.stream().filter(item -> ride_code_bus.equals(item.getScenePort())).findFirst().orElse(null);
            TblPointsSceneResp sceneMetro = sceneRespList.stream().filter(item -> ride_code_metro.equals(item.getScenePort())).findFirst().orElse(null);


            if (sceneBus != null) {
                PointsImpowerReq impower = new PointsImpowerReq();
//                impower.setMemberId(memberEntity.getId());
                impower.setMemberId(memberEntity.getUuid());
                impower.setCreateDate(new Date());
                impower.setStatus(0);
                impower.setPhone(phone);
                impower.setUnionId(unionId);
                impower.setSceneId(sceneBus.getId());
                impower.setScenePort(sceneBus.getScenePort());
                list.add(impower);
            }
            if (sceneMetro != null) {
                PointsImpowerReq impower = new PointsImpowerReq();
//                impower.setMemberId(memberEntity.getId());
                impower.setMemberId(memberEntity.getUuid());
                impower.setCreateDate(new Date());
                impower.setStatus(0);
                impower.setPhone(phone);
                impower.setUnionId(jsonObject.getString("unionId"));
                impower.setSceneId(sceneMetro.getId());
                impower.setScenePort(sceneMetro.getScenePort());
                list.add(impower);
            }

            //  授权回调场景结果通知tencent
            SceneEmpowerReqDTO reqDTO = null;
            for (PointsImpowerReq pointsImpowerReq : list) {
                reqDTO = new SceneEmpowerReqDTO();
                reqDTO.setMemberId(String.valueOf(pointsImpowerReq.getMemberId()));
                httpRequestService.postTanTanCallBackResultToTencent(reqDTO);
            }


            tblPointsImpowerService.saveImpowerMember(list);



            return CommonResult.success();
//        } catch (Exception e) {
//            log.error("无效数据", e);
//        }
//        return CommonResult.success();
    }

    private String generateSign(String timeStamp, String phone, String unionId) throws Exception {
        //有序 map
        Map<String, Object> map = new TreeMap<>();
        map.put("phone", phone);
        map.put("unionId", unionId);
        map.put("timeStamp", timeStamp);
        String str = JSON.toJSONString(map);
        //签名
        String sign = DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        return sign;
    }
}

